#include <typeinfo>
#include <iostream>
#include <cassert>


class Any
{
private:
    class holder
    {
    public:
        virtual ~holder(){}
        virtual const std::type_info& type() = 0;
        virtual holder *clone() = 0;
    };
 
    template <class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T &val) : _val(val)
        {
        }
        virtual const std::type_info& type()
        {
            return typeid(T);
        }
        virtual holder *clone()
        {
            return new placeholder(_val);
        }

    public:
        T _val;
    };



    holder *_content;
public:
    Any& swap(Any& other)
    {
        std::swap(_content,other._content);
        return *this;
    }

    Any()
        : _content(NULL)
    {
    }
    template <class T>
    Any(const T &val)
        :_content(new placeholder<T>(val))
    {
    }
    Any(const Any &other)
        : _content(other._content ? other._content->clone() : NULL)
    {
    }
    ~Any()
    {
        delete _content;
    }

    template <class T>
    T *get()
    {
        assert(typeid(T) == _content->type());
        return &((placeholder<T>*)_content)->_val;
    }



    Any &operator=(Any &other)
    {
        return other.swap(*this);
    }
    template <class T>
    Any &operator=(const T &val)
    {   
        return Any(val).swap(*this);
    }
};

class Test{
    public:
    Test()
    {
        std::cout<<"构造"<<std::endl;
    }
    Test(const Test& t)
    {
        std::cout<<"拷贝"<<std::endl;
    }
    ~Test()
    {
        std::cout<<"析构"<<std::endl;
    }
};

#include<string>
using namespace std;
int main()
{
    // Any a = 10;
    // int* b;
    // b = a.get<int>();
    // cout<<*b<<endl;

    // a = string("nihao");
    // string* c = a.get<string>();
    // cout<<*c<<endl;

    // Any d = a;
    //  c = d.get<string>();
    // cout<<*c<<endl;
    Test t;
    Any a = t;

    return 0;
}